<template>
  <div class="tg">
    <el-form ref="form" :model="form" label-width="80px" :rules="rules">
      <el-form-item label="视频标题" prop="title">
        <el-input v-model="form.title"></el-input>
      </el-form-item>

      <el-form-item label="类型" prop="type">
        <el-radio-group v-model="form.type">
          <el-radio label="0">原创</el-radio>
          <el-radio label="1">转载</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="封面上传" prop="coverPhoto">
        <el-upload
          class="avatar-uploader"
          :action="baseUrl+'uploadImg'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          accept="image/*"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="视频分区" prop="type2Id">
        <el-cascader
          expand-trigger="hover"
          :options="options"
          v-model="array"
          @change="handleChange"
          :props="props"
        ></el-cascader>
      </el-form-item>

      <el-form-item label="视频上传" prop="video">
        <el-upload
          class="upload-demo"
          :before-upload="beforeAvatarUpload2"
          drag
          :action="baseUrl+'uploadVideo'"
          :on-success="handleAvatarSuccess2"
          :on-progress="uploading"
          :show-file-list="false"
          accept="video/*"
        >
          <div v-if="!isUpload">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将视频拖到此处，或
              <em>点击上传</em>
            </div>
          </div>
          <div class="el-uploading">
            <el-progress
              v-if="isUpload"
              type="circle"
              :percentage="percent"
              :status="uploadstatus"
            >{{percent}}%</el-progress>
          </div>
          <div class="el-upload__tip" slot="tip">只能上传mp4文件，且不超过2G</div>
        </el-upload>
      </el-form-item>

      <el-form-item label="视频简介" prop="detail">
        <el-input
          type="textarea"
          :rows="5"
          placeholder="up主制作视频辛苦了，请up主为小观众们写一下视频简介吧，以便小观众们更好的了解视频"
          v-model="form.detail"
          resize="none"
          maxlength="255"
        ></el-input>
        <div class="font-count">{{fontCount}}/255</div>
      </el-form-item>

      <el-form-item label>
        <el-button type="primary" @click="submitForm('form')">提交</el-button>
        <el-button @click="resetForm('form')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "tg",
  data() {
    return {
      baseUrl: this.GLOBAL.baseUploadPath,
      imageUrl: "",
      isUpload: false,
      isUPloading: false, //是否上传中
      percent: 0, //文件上传百分比
      uploadstatus: "text",
      array: [],
      form: {
        title: "",
        detail: "",
        type: "0",
        coverPhoto: "",
        video: "",
        type1Id: "",
        type2Id: ""
      },
      rules: {
        coverPhoto: [
          { required: true, message: "图片不能为空!", trigger: "change" }
        ],
        title: [
          { required: true, message: "标题不能为空!" },
          { max: 30, message: "标题的最大长度为30个字符" }
        ],
        type: [{ required: true }],
        video: [
          { required: true, message: "请上传视频文件!", trigger: "change" }
        ],
        // type2Id: { required: true, message: "请选择视频分区" }
        array: { required: true, message: "请选择视频分区" }
      },
      options: [],
      props: {
        value: "id",
        label: "typeName"
      },
      selectedOptions: [],
      selectedOptions2: []
    };
  },
  mounted: function() {
    this.axios.post("video/getType").then(res => {
      this.options = res.data;
    });
  },
  methods: {
    //文件上传成功回调
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.coverPhoto = res.src;
    },
    handleAvatarSuccess2(res, file) {
      this.form.video = res.src;
      this.isUPloading = false;
    },
    //文件上传之前回调
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPng = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      const isJPGPNG = isJPG || isPng;

      if (!isJPGPNG) {
        this.$message.error("上传封面图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传封面图片大小不能超过 2MB!");
      }

      return isJPGPNG && isLt2M;
    },
    beforeAvatarUpload2(file) {
      this.uploadstatus = "text";
      const isMp4 = file.type === "video/mp4";
      const isAvi = file.type === "video/avi";
      const isLt2G = file.size / 1024 / 1024 / 1024 < 2;
      if (!isMp4&&!isAvi) {
        this.$message.error("上传视频只能是 mp4 格式!");
      }
      if(!isLt2G){
         this.$message.error("上传封面图片大小不能超过 2GB!");
      }

      return (isMp4||isAvi) && isLt2G;
      //return true
    },
    //文件上传中
    uploading(event, file, fileList) {
      console.log(event, file, fileList);
      this.isUpload = true;
      this.isUPloading = true;
      this.percent = Math.floor(event.percent);
      if (event.percent == 100) {
        this.uploadstatus = "success";
      }
    },
    //级联框选择
    handleChange(value) {
      this.form.type1Id = value[0];
      this.form.type2Id = value[1];
    },
    //提交表单
    submitForm(form) {
      this.form.type1Id = this.array[0];
      this.form.type2Id = this.array[1]; //预防重置
      this.form.userId = JSON.parse(localStorage.getItem("userData")).id;
      if(!this.form.userId){
        this.$message.error("您的登录状态失效，请重新登录!")
        return;
      }

      if (this.isUPloading) {
        this.$message("文件上传中,请上传完成后在提交！");
        return;
      }

      this.$refs[form]
        .validate()
        .then(valid => {
          this.axios.post("video/add", this.form).then(res => {
            if (res.data.success) {
              this.$alert("您已成功投稿，请耐心等待审核。");
              this.resetForm("form");
            }
          });
        })
        .catch(err => {
          console.log(err);
        });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.imageUrl = ""; //重置图片，一行代码搞定
      this.array = [];
      this.form.video = "";
      this.isUpload = false;
    }
  },
  computed: {
    fontCount: function() {
      return 255 - this.form.detail.length;
    }
  },
  watch: {
    array: function(val) {
      console.log(val);
    }
  }
};
</script>

<style lang="scss" scoped>
.font-count {
  text-align: right;
  color: #909399;
}
.el-uploading {
  margin: 20px 0 0 0;
  div {
    text-align: center;
  }
}
</style>